# coding=utf-8

import datetime
from datetime import timedelta, datetime
from flask import request
import uuid


class SessionIDManager:
    def __init__(self, app=None):
        if app is not None:
            self.init_app(app=app)

    def init_app(self, app):
        app.session_id_manager = self
        app.after_request(self._update_cookie)

    def _update_cookie(self, response):
        """注册到app.after_request, 当浏览器没有该cookie时，将会在应答头中带上该cookie"""
        if SessionIDManagerConfig.COOKIE_NAME not in request.cookies:
            duration = SessionIDManagerConfig.COOKIE_DURATION
            if isinstance(duration, int):
                duration = timedelta(seconds=duration)
            try:
                expires = datetime.utcnow() + duration
            except TypeError:
                raise Exception('SessionIDManagerConfig.COOKIE_DURATION must be a ' +
                                'datetime.timedelta, instead got: {0}'.format(duration))
            uuid_ = str(uuid.uuid1())
            response.set_cookie(SessionIDManagerConfig.COOKIE_NAME,
                                value=uuid_,  # 唯一标识
                                expires=expires,
                                domain=None,
                                path='/',
                                secure=SessionIDManagerConfig.COOKIE_SECURE,
                                httponly=SessionIDManagerConfig.COOKIE_HTTPONLY)
        else:
            pass
        return response

    def get_session_id(self) -> str:
        """获取当前会话的session_id"""
        return request.cookies.get(SessionIDManagerConfig.COOKIE_NAME)


class SessionIDManagerConfig:
    COOKIE_NAME = 'session_id'

    COOKIE_DURATION = timedelta(days=365)

    COOKIE_SECURE = None

    COOKIE_HTTPONLY = False
